import { ld } from '@/llmDialog'
import type { LDEvents, LDStateReactive } from '@/llmDialog/types'
import { nextTick } from 'vue'

export default function useHandleSend(
  state: LDStateReactive,
  { send: emitSend }: LDEvents,
  {
    scrollToBottom,
    isAtBottom,
  }: {
    scrollToBottom: () => void
    isAtBottom: () => boolean
  },
) {
  function send() {
    // 设置当前组件为发送状态
    state.isSending = true
    // 获取输入框的文本
    const prompt = state.editorText
    // 获取上传的文件列表
    const files = state.files.map((f) => f.file) as File[]
    // 清空输入框
    state.editorText = ''
    // 清空上传的文件
    state.files.splice(0, state.files.length)

    // 新增用户消息
    state.messages.push(ld.createUserMessage(prompt!))

    // 新增 LLM 消息
    state.messages.push(ld.createLLMMessage(''))



    // 追加消息到对话框
    const append = (text: string) => {
      if (state.messages.length === 0) return
      if (state.isSending === false) return
      const lastMessage = state.messages[state.messages.length - 1]
      if (lastMessage.type === 'llm') {
        lastMessage.content += text
      }
      // 尝试自动滚动到底部
      if (isAtBottom()) {
        nextTick(() => {
          scrollToBottom()
        })
      }
    }

    // 完成发送时的回调函数
    const done = () => {
      if (state.isSending === false) return
      state.isSending = false
    }
    // 触发发送事件
    emitSend(prompt!, files, append, done)
  }

  return {
    send,
  }
}
